<template>
  <div ref="emojiPickerDialog" :class="{
    'emoji-picker': true,
    'emoji-picker-h5': !isPC
  }">
    <ul ref="emojiPickerListRef" :class="['emoji-picker-list', !isPC && 'emoji-picker-h5-list']">
      <li v-show="currentEmojiList.length == 0">
        <div class="weui-emotion_list">
          <template v-for="(item, index) in emotions" :key="index">
            <div class="weui-emotion_item" :idx="index" @click="selectEmoji(item, index)">
              <div class="weui-icon_emotion" :class="item.style">
              </div>
            </div>
          </template>
        </div>
      </li>
      <li v-for="(childrenItem, childrenIndex) in currentEmojiList" :key="childrenIndex" class="emoji-picker-list-item"
        @click="select(childrenItem, childrenIndex)">
        <img v-if="currentTabItem.type === EMOJI_TYPE.BASIC" class="emoji"
          :src="currentTabItem.url + BASIC_EMOJI_URL_MAPPING[childrenItem]">
        <img v-else-if="currentTabItem.type === EMOJI_TYPE.BIG" class="emoji-big"
          :src="currentTabItem.url + childrenItem + '@2x.png'">
        <img v-else class="emoji-custom emoji-big" :src="currentTabItem.url + childrenItem">
      </li>
    </ul>
    <ul class="emoji-picker-tab">
      <li class="emoji-picker-tab-item" @click="toggleEmojiCustom">
        <Icon class="icon" :file="emojiIcon" />
      </li>
      <li v-for="(item, index) in list" :key="index" class="emoji-picker-tab-item" @click="toggleEmojiTab(index)">
        <Icon v-if="item.type === EMOJI_TYPE.BASIC" class="icon" :file="faceIcon" />
        <img v-else-if="item.type === EMOJI_TYPE.BIG" class="icon-big" :src="item.url + item.list[0] + '@2x.png'">
        <img v-else class="icon-custom icon-big" :src="item.url + item.list[0]">
      </li>
      <li v-if="isUniFrameWork" class="send-btn" @click="sendMessage">
        发送
      </li>
    </ul>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from '../../../../adapter-vue';
import {
  TUIChatService,
  TUIStore,
  StoreName,
  IConversationModel,
  SendMessageParams,
} from '@tencentcloud/chat-uikit-engine';
import Icon from '../../../common/Icon.vue';
import faceIconLight from '../../../../assets/icon/face-light.svg';
import faceIconDark from '../../../../assets/icon/face-dark.svg';
import toolEmoji from '../../../../assets/icon/emoji.svg';
import { EMOJI_TYPE } from '.././../../../constant';
import { isPC, isUniFrameWork } from '../../../../utils/env';
import { IEmojiGroupList, IEmojiGroup } from '../../../../interface';
import { isEnabledMessageReadReceiptGlobal } from '../../utils/utils';
import { EMOJI_GROUP_LIST, BASIC_EMOJI_URL_MAPPING, convertKeyToEmojiName } from '../../emoji-config';
import TUIChatConfig from '../../config';
import emojiData from './custom/emoji_data';
import emojiPanelData from './custom/emoji_panel_data';

const faceIcon = TUIChatConfig.getTheme() === 'dark' ? faceIconDark : faceIconLight;
const emojiIcon = toolEmoji;
const emits = defineEmits(['insertEmoji', 'onClose', 'sendMessage']);
const currentTabIndex = ref<number>(0);
const currentConversation = ref();
const emojiPickerDialog = ref();
const emojiPickerListRef = ref();
const featureConfig = TUIChatConfig.getFeatureConfig();
const list = ref<IEmojiGroupList>(initEmojiList());
const currentTabItem = ref<IEmojiGroup>(list?.value[0]);
const currentEmojiList = ref<string[]>([]);

const emotionMap = ref<any>({});
const emotionNames = ref<string[]>([]);
const emotions = ref<string[]>([]);

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  });
  emojiData.forEach(item => {
    emotionMap.value[item.id] = item
    emotionNames.value.push(item.name)
  })
  emojiPanelData.forEach(id => emotions.value.push(emotionMap.value[id]));
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  });
});

const toggleEmojiTab = (index: number) => {
  currentTabIndex.value = index;
  currentTabItem.value = list?.value[index];
  currentEmojiList.value = list?.value[index]?.list;
  // web & h5 side scroll to top
  if (!isUniFrameWork) {
    emojiPickerListRef?.value && (emojiPickerListRef.value.scrollTop = 0);
  }
};

const select = (item: any, index: number) => {
  const options: any = {
    emoji: { key: item, name: convertKeyToEmojiName(item) },
    type: currentTabItem?.value?.type,
  };
  switch (currentTabItem?.value?.type) {
    case EMOJI_TYPE.BASIC:
      options.url = currentTabItem?.value?.url + BASIC_EMOJI_URL_MAPPING[item];
      if (isUniFrameWork) {
        uni.$emit('insert-emoji', options);
      } else {
        emits('insertEmoji', options);
      }
      break;
    case EMOJI_TYPE.BIG:
      sendFaceMessage(index, currentTabItem.value);
      break;
    case EMOJI_TYPE.CUSTOM:
      sendFaceMessage(index, currentTabItem.value);
      break;
    default:
      break;
  }
  isPC && emits('onClose');
};

const sendFaceMessage = (index: number, listItem: IEmojiGroup) => {
  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID
      || currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload: {
      index: listItem.emojiGroupID,
      data: listItem.list[index],
    },
    needReadReceipt: isEnabledMessageReadReceiptGlobal(),
  } as SendMessageParams;
  TUIChatService.sendFaceMessage(options);
};

function sendMessage() {
  uni.$emit('send-message-in-emoji-picker');
}

function onCurrentConversationUpdate(conversation: IConversationModel) {
  currentConversation.value = conversation;
}

function initEmojiList() {
  return EMOJI_GROUP_LIST.filter((item) => {
    if (item.type === EMOJI_TYPE.BASIC) {
      return featureConfig.InputEmoji;
    }
    if (item.type === EMOJI_TYPE.BIG) {
      return featureConfig.InputStickers;
    }
  });
}

function toggleEmojiCustom() {
  currentTabItem.value = '';
  currentEmojiList.value = [];
}

const selectEmoji = (item: any, index: number) => {
  const options: any = {
    emoji: item,
    type: 'custom',
    url: `https://i.niuyuwang.com/emoji/${item.style}.png`
  };
  if (isUniFrameWork) {
    uni.$emit('insert-emoji', options);
  } else {
    emits('insertEmoji', options);
  }
}
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
@import './custom/emoji_positon.css';

.weui-emotion_list {
  padding: 0;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  width: 100%;
  height: 100%;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  white-space: normal;
  font-size: 0;
  display: flex;
  flex-wrap: wrap;
}

.weui-emotion_item {
  position: relative;
  width: 44px;
  height: 44px;
  padding-bottom: 5px;
  line-height: 44px;
}

.weui-icon_emotion {
  position: absolute;
  top: 4px;
  left: 4px;
  display: inline-block;
  transform-origin: 0 0;
  transform: scale(0.5);
  background-image: url('custom/emoji-sprite.png');
  background-repeat: no-repeat;
}

.weui-emotion_head {
  margin: 14px 5px 8px;
  color: #000;
  font-size: 14px;
  text-align: left;
}

.weui-emoji_area {
  position: relative;
  width: 100%;
}

.weui-emoji_area__has-safe-bottom {
  padding-bottom: 34px;
}

.weui-emotion_del_btn {
  display: inline-block;
  width: 24px;
  height: 24px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.weui-emoji__operation {
  position: absolute;
  bottom: 44px;
  right: 12px;
  // width: 120px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.weui-emoji__operation__delete,
.weui-emoji__operation__send {
  display: inline-block;
  width: 46px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  border-radius: 4px;
  font-size: 16px;
}

.weui-emoji__operation__delete {
  position: relative;
  font-size: 0;
  background-color: rgb(255, 255, 255);
}

.weui-emoji__operation__send {
  margin-left: 8px;
  background-color: #04C160;
  color: rgba(255, 255, 255, 0.9);
}
</style>
